package com.hmall.item.interceptor;

import com.hmall.item.utlis.UserHolder;
import com.mysql.jdbc.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //用完清理掉
        UserHolder.removeUser();
    }




    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //1获取请求头
        String authorization =request.getHeader("authorization");
        if (StringUtils.isEmptyOrWhitespaceOnly(authorization)){

            log.warn("非法用户访问！请求路径：{}",request.getRequestURI());
            //没有用户信息，未登录
            throw new RuntimeException("用户未登录");
        }
        //2.转换用户id
        Long userId =Long.valueOf(authorization);
        //3.存入ThreadLocal
        UserHolder.setUser(userId);
        //4.旅行
        return true;

    }
}